package dispatch

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"order_srv/basic/config"
	__ "order_srv/basic/orderproto"
	"order_srv/handler/models"
	"time"
)

func cacheKey(cityId uint32) string { return fmt.Sprintf("dispatch_cfg:%d", cityId) }

// GetParamsForCity 先读缓存，未命中则回源DB并写回缓存
func GetParamsForCity(in *__.DispatchConfigGetReq, ctx context.Context, cityId uint32) (Params, error) {

	var p Params
	var err error
	var user models.User
	user.Id = uint64(in.UserId)
	if err = user.GetUserId(); err != nil {
		return p, errors.New("用户不存在")
	}
	if user.CType != 1 {
		return p, errors.New("此用户未实名")
	}
	if user.UserRole != 3 {
		return p, errors.New("此用户不是管理员")
	}
	if config.Rdb != nil {
		if s, err := config.Rdb.Get(ctx, cacheKey(cityId)).Result(); err == nil && s != "" {
			_ = json.Unmarshal([]byte(s), &p)
			if p.CityId != 0 {
				return p, nil
			}
		}
	}

	// DB 回源
	cfg := models.DispatchConfig{}
	_ = cfg.GetByCityId(cityId)
	p = Params{
		CityId:              cityId,
		Strategy:            cfg.Strategy,
		MaxDistanceKM:       cfg.MaxDistanceKm,
		ScoreWeightDistance: cfg.ScoreWeightDistance,
		ScoreWeightRating:   cfg.ScoreWeightRating,
		ScoreWeightAccept:   cfg.ScoreWeightAccept,
		DayStartHour:        int(cfg.DayStartHour),
		NightStartHour:      int(cfg.NightStartHour),
		TimeWindowMinutes:   int(cfg.TimeWindowMinutes),
		Version:             cfg.Version,
	}

	if config.Rdb != nil {
		b, _ := json.Marshal(p)
		_ = config.Rdb.Set(ctx, cacheKey(cityId), string(b), 10*time.Minute).Err()
	}
	return p, nil
}
